'use client';

import { useEffect, useState } from 'react';
import { Card, Typography, Grid, Select, Input, Button, Message, Spin, Empty, Modal, Form, DatePicker, InputNumber } from '@arco-design/web-react';
import { roomApi, bookingApi } from '@/services/api';
import { Room, Booking } from '@/types';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';

const { Title, Text } = Typography;
const { Row, Col } = Grid;
const Option = Select.Option;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

export default function RoomsPage() {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(true);
  const [roomType, setRoomType] = useState<string | undefined>();
  const [bookingModalVisible, setBookingModalVisible] = useState(false);
  const [selectedRoom, setSelectedRoom] = useState<Room | null>(null);
  const [bookingLoading, setBookingLoading] = useState(false);
  const [totalDays, setTotalDays] = useState(1);
  const [totalAmount, setTotalAmount] = useState(0);
  const [form] = Form.useForm();

  const { isAuthenticated, user, userType } = useAuth();
  const router = useRouter();

  useEffect(() => {
    fetchRooms();
  }, [roomType]);

  const fetchRooms = async () => {
    setLoading(true);
    try {
      const response = roomType
        ? await roomApi.getAvailable(roomType)
        : await roomApi.getAvailable();

      console.log('获取房间列表响应:', response);

      if (response.code === 200 && response.data) {
        console.log('房间列表数据:', response.data);
        setRooms(response.data);
      } else {
        console.error('获取房间列表失败:', response);
        // Message.error(response.message || '获取房间列表失败');
      }
    } catch (error) {
      console.error('获取房间列表错误:', error);
      // Message.error('获取房间列表时发生错误');
    } finally {
      setLoading(false);
    }
  };

  const handleBookRoom = (room: Room) => {
    if (!isAuthenticated) {
      // Message.warning('请先登录后再预订房间');
      router.push('/login');
      return;
    }

    setSelectedRoom(room);
    setTotalAmount(room.price);
    setBookingModalVisible(true);
  };

  const handleDateChange = (dates: any) => {
    if (dates && dates.length === 2 && selectedRoom) {
      const startDate = new Date(dates[0]);
      const endDate = new Date(dates[1]);
      const diffTime = Math.abs(endDate.getTime() - startDate.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      setTotalDays(diffDays);
      setTotalAmount(diffDays * selectedRoom.price);
    }
  };

  const handleBookingSubmit = async (values: any) => {
    if (!selectedRoom) {
      console.error('未选择房间');
      return;
    }

    setBookingLoading(true);
    try {
      console.log('表单数据:', values);

      if (!values.dateRange || values.dateRange.length !== 2) {
        // Message.error('请选择入住和退房日期');
        return;
      }

      // 将日期字符串转换为 Date 对象
      const checkInDate = new Date(values.dateRange[0]);
      const checkOutDate = new Date(values.dateRange[1]);

      const bookingData: Omit<Booking, 'bookingID' | 'bookingTime' | 'customerID' | 'status'> = {
        roomId: selectedRoom.roomId!,
        checkInTime: checkInDate.toISOString(),
        checkOutTime: checkOutDate.toISOString(),
        totalAmount: totalAmount
      };

      console.log('提交的预订数据:', bookingData);

      const response = await bookingApi.create(bookingData);
      console.log('预订响应:', response);

      if (response.code === 200) {
        Message.success('预订成功');
        setBookingModalVisible(false);
        form.resetFields();
        fetchRooms(); // 刷新房间列表
        router.push('/bookings'); // 跳转到预订列表
      } else {
        // Message.error(response.message || '预订失败，请稍后重试');
      }
    } catch (error) {
      console.error('预订错误:', error);
      // Message.error('预订过程中发生错误');
    } finally {
      setBookingLoading(false);
    }
  };

  const roomTypeOptions = [
    { label: '所有类型', value: '' },  // 将undefined改为空字符串
    { label: '标准间', value: '标准间' },
    { label: '豪华间', value: '豪华间' },
    { label: '套房', value: '套房' },
    { label: '商务间', value: '商务间' },
  ];

  return (
    <div className="py-6">
      <div className="flex justify-between items-center mb-6">
        <Title heading={3}>可用房间</Title>

        <div className="flex items-center space-x-4">
          <Select
            placeholder="选择房间类型"
            style={{ width: 160 }}
            value={roomType}
            onChange={setRoomType}
          >
            {roomTypeOptions.map(option => (
              <Option key={option.value || 'all'} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>

          <Button type="primary" onClick={() => fetchRooms()}>
            刷新
          </Button>
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center py-12">
          <Spin />
        </div>
      ) : rooms.length > 0 ? (
        <Row gutter={[16, 16]}>
          {rooms.map(room => (
            <Col key={room.roomId} xs={24} sm={12} md={8} lg={6}>
              <Card
                className="h-full"
                actions={[
                  <Button key="book" type="primary" onClick={() => handleBookRoom(room)}>
                    预订
                  </Button>
                ]}
              >
                <div className="mb-2">
                  <Text bold>房间号: {room.roomNumber}</Text>
                </div>
                <div className="mb-2">
                  <Text type="secondary">类型: {room.roomType}</Text>
                </div>
                <div className="mb-2">
                  <Text type="secondary">状态: {room.status}</Text>
                </div>
                <div>
                  <Text bold type="success">价格: ¥{room.price}/晚</Text>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      ) : (
        <Empty description="暂无可用房间" />
      )}

      <Modal
        title="预订房间"
        visible={bookingModalVisible}
        onCancel={() => {
          setBookingModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        style={{ maxWidth: '500px' }}
        maskClosable={false}
        unmountOnExit={true}
        autoFocus={true}
        focusLock={true}
        className="booking-modal"
      >
        {selectedRoom && (
          <div className="booking-form">
            <div className="mb-6 p-4 bg-gray-50 rounded">
              <Title heading={5}>房间信息</Title>
              <div className="grid grid-cols-2 gap-4 mt-2">
                <div>
                  <Text type="secondary">房间号:</Text>
                  <div><Text bold>{selectedRoom.roomNumber}</Text></div>
                </div>
                <div>
                  <Text type="secondary">房间类型:</Text>
                  <div><Text bold>{selectedRoom.roomType}</Text></div>
                </div>
                <div>
                  <Text type="secondary">价格:</Text>
                  <div><Text bold type="success">¥{selectedRoom.price}/晚</Text></div>
                </div>
                <div>
                  <Text type="secondary">状态:</Text>
                  <div><Text bold>{selectedRoom.status}</Text></div>
                </div>
              </div>
            </div>

            <Form
              form={form}
              layout="vertical"
              onSubmit={handleBookingSubmit}
              initialValues={{
                guests: 1
              }}
            >
              <FormItem
                label="入住和退房日期"
                field="dateRange"
                rules={[{ required: true, message: '请选择入住和退房日期' }]}
              >
                <RangePicker
                  style={{ width: '100%' }}
                  onChange={handleDateChange}
                  disabledDate={(current) => current.isBefore(new Date(), 'day')}
                />
              </FormItem>

              <FormItem
                label="入住人数"
                field="guests"
                rules={[{ required: true, message: '请输入入住人数' }]}
              >
                <InputNumber
                  min={1}
                  max={4}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <div className="mb-6 p-4 bg-blue-50 rounded">
                <div className="flex justify-between items-center">
                  <Text>住宿天数:</Text>
                  <Text bold>{totalDays}晚</Text>
                </div>
                <div className="flex justify-between items-center mt-2">
                  <Text>总价:</Text>
                  <Text bold type="success" style={{ fontSize: '18px' }}>¥{totalAmount}</Text>
                </div>
              </div>

              <FormItem>
                <div className="flex space-x-4">
                  <Button
                    type="primary"
                    htmlType="submit"
                    long
                    loading={bookingLoading}
                  >
                    确认预订
                  </Button>
                  <Button
                    type="secondary"
                    long
                    onClick={() => {
                      setBookingModalVisible(false);
                      form.resetFields();
                    }}
                  >
                    取消
                  </Button>
                </div>
              </FormItem>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  );
}